package com.template.config.webmvc.interceptor;

import com.template.common.lang.BaseContext;
import com.template.common.annotation.Authority;
import com.template.common.exception.PermissionException;
import com.template.service.SysUserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;
import java.util.List;

/**
 * 权限验证，接口访问权限拦截器
 */
@Component
@RequiredArgsConstructor
public class UserPermissionInterceptor implements HandlerInterceptor {

    private final SysUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod handlerMethod)) return true;

        // 判断接口所需要的权限
        Authority annotation = handlerMethod.getMethod().getAnnotation(Authority.class);
        // 未有权限注解，直接放行
        if (annotation == null) return true;

        // 获取接口所需要的权限
        String[] auths = annotation.value();

        // 获取用户所拥有的权限
        Long userId = BaseContext.getCurrentId();
        List<String> userAuths = userService.getUserPerms(userId);

        // 判断用户是否拥有接口的权限
        for (String auth : auths) {
            if (userAuths.contains(auth)) {
                return true;
            }
        }

        // 用户未有该接口的权限，拦截
        throw new PermissionException();
    }

}
